import {getCookie, getLocalStorage, removeLocalStorage, setCookie, setLocalStorage} from "./cache";
import {post} from "./http";

window.showHN = false;//全局的header显示 全局的nav显示
//将undefined的字符串转成""
export var parseUndefined = function (v){
    return (v==undefined?"":v);
}
//去除v右边的k
export var trim = function (v,k){
    if (v.lastIndexOf(k)==v.length-k.length){
        return v.substring(0, v.lastIndexOf(k));
    }else{
        return v;
    }
}
//防止vue监听出现循环 c是循环的次数，func是需要执行的程序函数，会自动拦截掉事件监听
export var loopC = function(func){
    if(loopConst > 0){
        loopConst = loopConst-1;
        func();
        loopC(func)
    }else{
        loopConst = 1;
    }
};
//返回 $_GET 对象, 仿PHP模式
export var $_GET = (function(){
    var url = window.document.location.href.toString();
    var u = url.split("?");
    for (let i_ in u){
        if(u[i_].indexOf("/")<0){
            if(typeof(u[i_]) == "string"){
                var u_ = u[i_].split("&");
                var get = {};
                for (let i in u_){
                    var j = u_[i].split("=");
                    get[j[0]] = j[1];
                }
                return get;
            } else {
                return {};
            }
        }
    }
    return {};
})();
//返回 $_GET 对象, 仿PHP模式
export var getHttp = function(){
    var url = window.document.location.href.toString();
    var u = url.split("?");
    for (let i_ in u){
        if(u[i_].indexOf("/")<0){
            if(typeof(u[i_]) == "string"){
                var u_ = u[i_].split("&");
                var get = {};
                for (let i in u_){
                    var j = u_[i].split("=");
                    get[j[0]] = j[1];
                }
                return get;
            } else {
                return {};
            }
        }
    }
    return {};
};
//返回 $_GET 对象, 仿PHP模式
export var $_GETURL = (function(){
    var url = window.document.location.href.toString();
    return url;
})();
//获得形式为$GET("asd?asd=23")['asd']
export var $GET = function(url){
    var u = url.split("?");
    if(typeof(u[1]) == "string"){
        u = u[1].split("&");
        var get = {};
        for(var i in u){
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
};
//判断父存在的子是否存在，存在就返回false,表示，父就不需要监听
export function judgeExit(children,that,temp) {
    var chil = true;
    if (children!=undefined){
        for (var j in children) {
            if(children[j] !="#" && $(children[j]).find("["+temp+"='"+$(that).attr(temp)+"']").length>0){
                chil = false;
            }
        }
    }
    return chil;
}
/**
 * 让所有数据进行反转
 * @param that
 */
export var revertData = function (datas) {
    if (typeof datas == "object"){
        for (let item in datas){
            if (typeof eval("datas."+item) == "object"){
                flushData(item)
            }
            vue.$set(datas,item,!eval("datas."+item))
        }
    }
}
/**
 * 拿到当前的时间
 * @param that
 */
export var getTime = function (time) {
    function getNow(s) {
        return s < 10 ? '0' + s: s;
    }
    var myDate = time;
    //获取当前年
    var year=myDate.getFullYear();
    //获取当前月
    var month=myDate.getMonth()+1;
    //获取当前日
    var date=myDate.getDate();
    var h=myDate.getHours();       //获取当前小时数(0-23)
    var m=myDate.getMinutes();     //获取当前分钟数(0-59)
    var s=myDate.getSeconds();
    var now=year+'年'+getNow(month)+"月"+getNow(date)+"日 "+getNow(h)+'时'+getNow(m)+"分"+getNow(s)+"秒";
    return now;
}
/**
 * 拿到时间的时间戳
 * @param that
 */
export var getTimeStamp = function (time,length=13) {
    var t = time.getTime().toString();
    return t.substr(0,length);
}
/**
 * 拿到 今天 昨天 凌晨  时间的时间戳
 * day == 0 表示是今天，-1是昨天 ,1是明天凌晨
 * @param that
 */
export var getDayStartTimeStamp = function (day=0) {
    var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
    //一天是86400秒   故n天前的时间戳为
    return timeStamp + 86400 * day;
}
/**
 * 防止发生 layui的 事件冒泡
 * @returns {string}
 */
export var stopLayPop = function () {
    $("button").click(function () {
        //阻止事件的冒泡发生，
        event.returnValue = false;
        event.preventDefault();
        event.cancelBubble = true;
        event.stopPropagation();
    })
}
/**
 * 遍历该组件的所有子组件
 * @param children 是一个数组 []
 * @param that 是对象
 * @param func1 是函数1
 * @param func2 函数2
 */
export var xunhuan = function(children,that,func1,func2){
    if (that.$children.length>0){
        for (var item in that.$children){
            if (that.$children[item].$el.id!=""){
                if (that.$children[item].$children.length > 0) {
                    xunhuan(children,that.$children[item],func1,func2);
                    func1(children,that.$children[item]);
                    children.push("#"+that.$children[item].$el.id);
                }else{
                    func2(that.$children[item])
                    children.push("#"+that.$children[item].$el.id);
                    xunhuan(children,that.$children[item],func1,func2)
                }
            }
        }
    }
}
/**
 * 下载文件
 * name 是需要下载后得到的文件名字 比如： 0000.xls
 * file 是文件的网络路径 比如：https://10.105.203.200/crms/backend/web/uploads/yuyin/18/1023/4epcr6.xls
 * path 下载文件的接口  默认是cti-manager/download-file
 */
export var downloadFile = function (name,file,path='cti-manager/download-file') {
    var url = burl+path;
    // 分装form表单
    var form = $("<form target='_blank'></form>").attr("action", url).attr("method", "post");
    // 封装参数
    form.append($("<input></input>").attr("type", "hidden").attr("name", "file").attr("value",file));
    form.append($("<input></input>").attr("type", "hidden").attr("name", "name").attr("value",name));
    // 提交
    form.appendTo('body').submit().remove();
}
/**
 * 拿到身份城市区县
 * @param selectArea 地区数组 common/js/select_area.js中的数组
 * @param sfcsqx_ 已经选中的数组 比如['1102020','1020202','122333']
 * @returns {string}
 */
export var getSfcsqx = function(selectArea,sfcsqx_){
    if (sfcsqx_!==undefined&&sfcsqx_!==null){
        let sfcsqx = JSON.parse(sfcsqx_);
        let sf = selectArea.filter((item)=>{
            return item.value==sfcsqx[0];
        });
        let sf_ = sf[0]['children'];
        let sf__ = sf[0]['label'];
        let cs = sf_.filter((item)=>{
            return item.value==sfcsqx[1];
        });
        let cs_ = cs[0]['children'];
        let cs__ = cs[0]['label'];
        let qx = cs_.filter((item)=>{
            return item.value==sfcsqx[2];
        });
        let qx__ = qx[0]['label'];
        return sf__+'/'+cs__+'/'+qx__;
    }else{
        return '';
    }
}

/**
 * 查询ip
 * @param onNewIP
 */
export function findIP(onNewIP) { //  onNewIp - your listener function for new IPs
    var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
    var pc = new myPeerConnection({iceServers: []}), // 空的ICE服务器（STUN或者TURN）
        noop = function() {},
        localIPs = {}, //记录有没有被调用到onNewIP这个listener上
        ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
        key;
    function ipIterate(ip) {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
    }
    pc.createDataChannel(""); //create a bogus data channel
    pc.createOffer().then(function(sdp) {
        sdp.sdp.split('\n').forEach(function(line) {
            if (line.indexOf('candidate') < 0) return;
            line.match(ipRegex).forEach(ipIterate);
        });
        pc.setLocalDescription(sdp, noop, noop);
    }); // create offer and set local description
    pc.onicecandidate = function(ice) { //listen for candidate events
        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
        ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
    };
}
export function addIP(ip) {
    setCookie('ip',ip);
}

/**
 * 拿到本地的ip 变量存储在window.IP中
 */
export var getIp = function () {
    findIP(addIP);
}
/**
 * 写日志
 * @param c 内容
 * @param color 颜色
 */
export var writeLogs = function (color='black',content) {//状态字符初始化，done为true表示是点击了签入、拨打电话等按钮
    let temp = getLocalStorage('myLogs')
    if (temp === undefined || temp === '' || temp === null){
        temp = []
        setLocalStorage('myLogs',temp)
    }
    let data = {Mylogs:{
            color:color==''?'black':color
            ,operatorZuoxi:getCookie('zuoxi')
            ,operatorUsername:getCookie('user')
            ,operatorYggh:getCookie('yggh')
            ,operatorUserid:getCookie('gsid')
            ,operateIp:getCookie('ip')
            ,operateTime:getTimeStamp(new Date())
            ,operateContent:content}}
    temp.push(data)
    setLocalStorage('myLogs',temp)
    if (writeLogsStatus===0) {//开启 有日志就立马写到服务器
        post('logs/write',{data:data})
            .then((res)=>{
                if (res.data.res==1){
                    removeLocalStorage('myLogs')
                }
            }).catch((res)=>{
            consoleLog(res)
        })
    }
}